package com.hgzy.sys.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hgzy.sys.common.ActiveUser;
import com.hgzy.sys.domain.User;
import com.hgzy.sys.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Wrapper;

/**
 * @author : look-word
 * @date : 2022-01-14 14:21
 **/
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    /**
     * 获取当前类名
     * @return 当前类名
     */
    @Override
    public String getName() {
        return this.getClass().getName();
    }

    /**
     * 授权
     * @param principalCollection 授权控制器
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param token 认证
     * @return null 表示未认证
     * @throws AuthenticationException 密码或用户名不正确
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        // 比对用户名是否一致
        wrapper.eq("loginname",token.getPrincipal().toString());
        User user = userService.getOne(wrapper);
        if (user != null) {
            ActiveUser activeUser = new ActiveUser();
            activeUser.setUser(user);
            //  获取当前的盐
            ByteSource credentials = ByteSource.Util.bytes(user.getSalt());
            // 将认证信息返回
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activeUser,user.getPwd(),credentials,getName());
            return info;
        }
        return null;
    }
}
